<!--  -->
<template>
  <div class="home">
    <el-container>
      <!-- 头部 -->
      <el-header :style="{ backgroundColor: themeColor }">
        <div :style="{ color: fontColor }" class="app-name">{{userinfo.nickname}}音乐库</div>
        <div :style="{ color: fontColor }" class="icon">
          <i
            :style="{ color: fontColor }"
            class="el-icon-arrow-left"
            @click="back"
          ></i>
          <i
            :style="{ color: fontColor }"
            class="el-icon-arrow-right"
            @click="advance"
          ></i>
        </div>
        <div class="input">
          <el-popover
            placement="bottom"
            title="搜索历史"
            width="320"
            trigger="click"
            v-model="visible"
          >
            <div class="search_wrap">
              <div class="search_his">
                <div
                  @click="deleteHis"
                  class="iconfont iconshanchu delete"
                ></div>
                <div
                  v-for="(item, index) in historyList"
                  :key="index"
                  class="search_item"
                  @click="toList(item)"
                >
                  {{ item }}
                </div>
              </div>
              <div v-show="searchData == ''" class="hot_search">
                <div class="header">热搜榜</div>
                <div class="hot_item">
                  <div
                    @click="toList(item.searchWord)"
                    v-for="(item, index) in searchList"
                    :key="index"
                    class="item"
                  >
                    <div class="num">{{ index + 1 }}</div>
                    <div class="content">
                      <div class="title">
                        <div class="title_name">{{ item.searchWord }}</div>
                        <div v-if="item.iconUrl" class="img">
                          <img :src="item.iconUrl" alt="" />
                        </div>
                        <div class="score">
                          {{ item.score }}
                        </div>
                      </div>
                      <div class="der">{{ item.content }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-show="searchData" class="suggest_search">
                <div class="suggest_item">
                  <div v-show="suggestList.songs" class="item">
                    <div class="title el-icon-headset">单曲</div>
                    <div
                      v-for="(item1, index1) in suggestList.songs"
                      :key="index1"
                      class="content"
                    >
                      <div @click="toList(item1.name)">{{ item1.name }}</div>
                    </div>
                  </div>
                  <div v-show="suggestList.albums" class="item">
                    <div class="title el-icon-orange">专辑</div>
                    <div
                      v-for="(item1, index1) in suggestList.albums"
                      :key="index1"
                      class="content"
                    >
                      <div @click="toAlbum(item1.id)">{{ item1.name }}</div>
                    </div>
                  </div>
                  <div v-show="suggestList.playlists" class="item">
                    <div class="title el-icon-s-operation">歌单</div>
                    <div
                      v-for="(item1, index1) in suggestList.playlists"
                      :key="index1"
                      class="content"
                    >
                      <div @click="toPlayList(item1.id)">{{ item1.name }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-input
              slot="reference"
              placeholder="搜索"
              v-model="searchData"
              @input="handleInput(searchData)"
              @keyup.enter.native="toList(searchData)"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-search"
                @click="toList(searchData)"
              ></i>
            </el-input>
          </el-popover>
        </div>

        <div v-if="loginStatus === 'false'" class="user">
          <div class="user-cover">
            <img
              @click="centerDialogVisible = true"
              src="../assets/img/youke.gif"
              alt=""
            />
          </div>
          <div class="user-name">未登录</div>
        </div>
        <div v-if="loginStatus === 'true'" class="user">
          <div class="user-cover">
            <img @click="showUserInfo" :src="userinfo.avatarUrl" alt="" />
          </div>
          <div :style="{ color: fontColor }" class="user-name">
            {{ userinfo.nickname }}
          </div>
        </div>
        <div v-if="loginStatus == 'true'" class="sign_in">
          <div
            :style="{ color: fontColor }"
            @click="Sign"
            v-if="!isSign"
            class="sign el-icon-coin"
          >
            签到
          </div>
          <div :style="{ color: fontColor }" v-else class="sign">已签到</div>
        </div>

        <div class="theme">
          <el-color-picker
            @change="changeTheme"
            v-model="themeColor"
            size="mini"
          >
          </el-color-picker>
        </div>
        <div v-if="loginStatus == 'true'" class="message">
          <i
            :style="{ color: fontColor }"
            @click="dialogVisible = !dialogVisible"
            class="el-icon-message"
          ></i>
        </div>
        <div v-show="loginStatus === 'true'" class="exit">
          <el-button @click="exit" size="mini">退出</el-button>
        </div>
        <el-dialog
          top="0"
          width="0"
          :show-close="false"
          :modal="false"
          :visible.sync="dialogVisible"
        >
          <Message class="message_wrap"></Message>
        </el-dialog>

        <el-dialog
          top="0"
          width="0"
          :show-close="false"
          :modal="false"
          :visible.sync="centerDialogVisible"
        >
          <Login class="login" @func="isShow"></Login>
        </el-dialog>
      </el-header>

      <el-container>
        <el-aside width="200px">
          <LeftNav class="leftNav"></LeftNav>
        </el-aside>
        <el-main>
          <keep-alive exclude="userinfo">
            <router-view ref="child" :key="$route.fullPath"></router-view>
          </keep-alive>
        </el-main>
      </el-container>

      <el-footer height="75px">
        <MusicPlay></MusicPlay>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import LeftNav from "views/home/leftNav/LeftNav.vue";
import Login from "views/home/login/Login.vue";
import Message from "@/views/home/message/Message.vue";
import MusicPlay from "components/content/MusicPlay";

import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import { getHotSearch } from "util/songListPage";
import {
  getSearchList,
  getSearchHistory,
  getSearchSuggest,
} from "util/findMusic";
import {
  getLogin,
  signIn,
  getUserPrivatePlayList,
  getSignInfo,
} from "util/login";
export default {
  name: "",
  components: {
    LeftNav,
    Login,
    MusicPlay,
    Message,
  },
  data() {
    return {
      searchData: "",
      isShowLogin: false,
      searchList: [],
      visible: false,
      historyList: localStorage.getItem("historyList")
        ? JSON.parse(localStorage.getItem("historyList"))
        : [],
      searchListData: [],
      centerDialogVisible: false,
      dialogVisible: false,
      //是否匹配搜索
      isSuggest: false,
      //搜索建议列表
      suggestList: {},
      btn_color: "red",
      themeColor: localStorage.getItem("themeColor")
        ? localStorage.getItem("themeColor")
        : "#fff",
      fontColor: localStorage.getItem("fontColor")
        ? localStorage.getItem("fontColor")
        : "#969292",
    };
  },
  computed: {
    ...mapGetters("userInfo", [
      //个人信息
      "userinfo",
      //登录状态
      "loginStatus",
      //签到状态
      "isSign",
    ]),
  },
  created() {
    this.getHotSearch();
    this.getCookie();
    //乐签信息
    // this.getSignInfo()
  },
  methods: {
    async getHotSearch() {
      let {
        data: { data },
      } = await getHotSearch();
      // console.log(data);
      this.searchList = data;
    },
    back() {
      this.$router.go(-1);
    },
    advance() {
      this.$router.go(1);
    },
    isShow(val) {
      this.centerDialogVisible = val;
    },
    //跳转搜索信息列表
    toList(keyword) {
      if (keyword) {
        this.$router.push("/searchList/" + keyword);
      }
      this.visible = false;
      if (this.historyList.indexOf(keyword) !== -1) {
        this.historyList.splice(this.historyList.indexOf(keyword), 1);
      }
      this.historyList.unshift(keyword);

      localStorage.setItem("historyList", JSON.stringify(this.historyList));
      this.historyList = JSON.parse(localStorage.getItem("historyList"));
    },
    //删除历史搜索记录
    deleteHis() {
      if (this.historyList.length > 0) {
        this.$confirm("确认删除历史记录?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.historyList = [];
            localStorage.clear("historyList");
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    showUserInfo() {
      // console.log(this.userinfo.userId)
      this.$router.push("/userInfo/" + this.userinfo.userId);
    },
    toAlbum(id) {
      this.visible = false;

      this.$router.push("/albumDetail/" + id);
    },
    toPlayList(id) {
      this.visible = false;

      this.$router.push("/songListPage/" + id);
    },
    //处理模糊匹配
    async handleInput(keyword) {
      if (!keyword) {
        return;
      } else {
        var isSend = false;
        if (isSend) {
          return;
        }
        isSend = true;
        this.getSearchData(keyword);
        setTimeout(() => {
          isSend = false;
        }, 1000);
      }
    },
    //获取搜索建议
    async getSearchData(keyword) {
      let {
        data: { result },
      } = await getSearchSuggest(keyword);
      this.suggestList = result;
    },

    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    },
    //换肤
    changeTheme(e) {
      if (e == null) {
        this.fontColor = "#969292";
        localStorage.clear("themeColor");
        localStorage.setItem("fontColor", "#969292");
      } else if (e.split("")[1] === "F") {
        this.fontColor = "#969292";
        localStorage.clear("themeColor");
        localStorage.setItem("fontColor", "#969292");
      } else {
        localStorage.setItem("themeColor", e);
        localStorage.setItem("fontColor", "#fff");
        this.fontColor = "#fff";
      }
    },

    //退出功能
    exit() {
      this.$confirm("是否退出账号?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //保存用户信息
          this.$store.dispatch("userInfo/saveUserInfo", {});

          //保存用户登录状态
          this.$store.dispatch("userInfo/saveLoginStatus", "false");
          sessionStorage.setItem("loginStatus", "false");

          //保存用户歌单信息
          this.$store.dispatch("userInfo/savePrivatePlayList", []);
          sessionStorage.clear(
            "userinfo",
            "userPrivatePlayList",
            "userId",
            "cookie",
            "isSign"
          );
          this.clearCookie();
          //保存用户id
          this.$store.dispatch("userInfo/saveUserId", "");
          this.$store.dispatch("userInfo/saveIsSign", false);
          this.$message({
            type: "success",
            message: "退出成功!",
          });
        })
        .catch(() => {});
    },
    //签到功能
    async Sign() {
      let { data } = await signIn();
      if (data.code == 200) {
        this.$message("签到成功");
        this.$store.dispatch("userInfo/saveIsSign", true);
        sessionStorage.setItem("isSign", true);
      }
    },
    //自动登录
    async getCookie() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] == "userName") {
            //  console.log(arr2[1])
            var username = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == "userPwd") {
            // console.log(arr2[1])
            var password = arr2[1];
          }
        }
        let { data } = await getLogin(username, password);
        //保存用户信息
        this.$store.dispatch("userInfo/saveUserInfo", data.profile);
        sessionStorage.setItem("userinfo", JSON.stringify(data.profile));
        //保存用户登录状态
        this.$store.dispatch("userInfo/saveLoginStatus", "true");
        sessionStorage.setItem("loginStatus", "true");
        //获取用户私人歌单
        let {
          data: { playlist },
        } = await getUserPrivatePlayList(data.profile.userId);
        // console.log(playlist);
        //保存用户歌单信息
        this.$store.dispatch("userInfo/savePrivatePlayList", playlist);
        sessionStorage.setItem("userPrivatePlayList", JSON.stringify(playlist));
        //保存用户id
        this.$store.dispatch("userInfo/saveUserId", data.profile.userId);
        sessionStorage.setItem("userId", data.profile.userId);
        //获取cookie
        sessionStorage.setItem("token", data.token);
        sessionStorage.setItem("cookie", data.cookie);
      }
    },
    //获取乐签信息
    async getSignInfo() {
      let res = await getSignInfo();
      console.log(res);
    },
  },
};
</script>

<style scoped lang='less'>
.el-header {
  width: 100%;
  position: fixed;
  z-index: 999;
  // position: relative;
  padding: 0 6.25rem;
  // background: rgb(209, 41, 35);
  background: #fff;
  display: flex;
  // box-shadow: 0 0 5px rgba(0, 0, 0, .1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.app-name {
  width: 13rem;
  line-height: 60px;
  font-size: 1.45rem;
  color: rgb(155, 151, 151);
  margin-left: 10px;
  font-weight: 600;
}
.icon {
  width: 3.75rem;
  display: flex;
  justify-content: center;
  align-items: center;
}
.icon i {
  font-size: 25px;
  font-weight: 600;
  font-weight: 600;
  color: rgb(136, 134, 134);
  margin-right: 10px;
}
.icon i:hover {
  background-color: rgba(155, 148, 148, 0.788);
  border-radius: 5px;
  color: rgb(68, 19, 19) !important;
}
.input {
  margin-left: 10px;
  line-height: 60px;
  /deep/ .el-input__inner {
    height: 33px;
    border: none;
    border-radius: 9px;
    background-color: rgba(214, 211, 211, 0.212);
    // background-color: #e13e3e;
  }
}
.user {
  display: flex;
  line-height: 60px;
  margin-left: 16.75rem;
}
.user-cover {
  width: 30px;
  height: 30px;
  margin-top: 10px;
  margin-right: 8px;
}
.user-cover img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.user-name {
  width: 3.25rem;
  font-size: 0.625rem;
  font-weight: 600;
  color: rgb(150, 146, 146);
}
.login {
  // width: 500px;
  z-index: 9;
  background: #fff; /* fallback for old browsers */
  position: absolute;
  top: 60px;
  left: 55%;
}
.message_wrap {
  z-index: 9;
  background: #fff; /* fallback for old browsers */
  position: absolute;
  top: 60px;
  // left: 400px;
  right: 0;
}
/deep/.el-dialog__wrapper .el-dialog {
  position: static;
}
.el-container .el-aside {
  margin-top: 60px;
  margin-bottom: 75px;
  height: calc(100vh - 135px);
  // height: 100%;
  position: fixed;
  overflow-y: scroll;
  &::-webkit-scrollbar {
  display: none;
}

}
.el-main {
  margin: 0;
  margin-top: 60px;
  margin-left: 200px;
  padding: 0;
  margin-bottom: 100px;
}
.el-footer {
  background: #fff;
  color: #333;
  text-align: center;
  line-height: 75px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9;
  display: flex;
  border-top: 2px solid #eee;
}
.search_wrap {
  cursor: pointer;
  .search_his {
    position: relative;
    height: 60px;
    overflow: hidden;
    // background-color: #ccc;
    display: flex;
    flex-wrap: wrap;
    .delete:hover {
      color: #666;
    }
    .delete {
      position: absolute;
      right: 3px;
      font-size: 25px;
      color: rgb(189, 182, 182);
    }
    .search_item {
      height: 18px;
      line-height: 18px;
      margin-bottom: 10px;
      border: #d9d9d9 1px solid;
      margin-right: 8px;
      padding: 2px 12px;
      border-radius: 20px;
      font-size: 10px;
    }
    .search_item:hover {
      background-color: #ddd;
    }
  }
  .hot_search::-webkit-scrollbar {
    display: none;
  }
  .hot_search {
    height: 700px;
    overflow-y: scroll;
    overflow-x: hidden;
    .header {
      margin: 10px 0;
      color: #666;
    }
    .hot_item {
      .item:hover {
        background-color: rgba(224, 220, 220, 0.596);
      }
      .item {
        height: 40px;
        background: #fff;
        display: flex;
        padding: 10px;
        align-items: center;
        .num {
          text-align: center;
          width: 30px;
          color: red;
          font-size: 18px;
        }
        .content {
          margin-left: 20px;
          display: flex;
          flex-direction: column;
          .title {
            display: flex;
            line-height: 20px;
            height: 20px;
            // align-items: center;
            .title_name {
              color: #333;
              font-weight: 600;
              font-size: 13px;
            }
            .img {
              margin-top: 1.5px;
              margin-left: 10px;
              width: 22px;
              height: 12px;
              img {
                width: 100%;
                height: 100%;
              }
            }
            .score {
              margin-left: 8px;
              color: rgb(204, 200, 200);
              font-size: 2px;
            }
          }
          .der {
            width: 240px;
            line-height: 24px;
            height: 20px;
            font-size: 8px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
  .suggest_search {
    height: 400px;
    .suggest_item {
      .item {
        .title {
          font-size: 14px;
          height: 40px;
          line-height: 40px;
          color: rgb(187, 183, 183);
        }
        .content {
          font-size: 12px;
          div {
            padding-left: 15px;

            height: 30px;
            line-height: 30px;
          }
          div:hover {
            background-color: #eee;
          }
        }
      }
    }
  }
}

.el-input {
  border-radius: 50%;
}
.message {
  margin-left: 0px;
  display: flex;
  justify-content: center;
  align-items: center;
  i {
    font-size: 22px;
  }
  i:hover {
    color: rgb(32, 7, 7) !important;
  }
}
.exit {
  margin-left: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.sign_in {
  // width: 3.75rem;
  cursor: pointer;
  margin-left: 0.525rem;
  display: flex;
  justify-content: center;
  align-items: center;
  .sign {
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 0.625rem;
    color: rgb(146, 140, 140);
    font-weight: 600;
  }
  .sign:hover {
    color: rgb(39, 7, 7) !important;
  }
}
.theme {
  padding: 0 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  /deep/.el-color-picker {
    .el-color-picker__trigger {
      .el-color-picker__color {
      }
    }
  }

  div {
    font-size: 20px;
    color: rgba(110, 103, 103, 0.733);
  }
  div:hover {
    color: rgb(27, 6, 6);
  }
}
</style>